# -*- coding:utf-8 -*-


from itertools import accumulate
import sys,os
sys.path.append(os.path.abspath('..'))
from csi_data import CSI_Data

max_antenna = 3


def read_from_csifile(filename):
    ret = []
    try:
        with open(filename, 'rb') as f:
            f.seek(0, 2)
            size = f.tell()
            f.seek(0, 0)
            cur = 0
            count = 0
            broken_perm = 0
            triangle = list(accumulate(range(1, max_antenna + 1)))
            while cur < size - 3:
                tmp = f.read(2)
                field_len = tmp[0] * 256 + tmp[1]
                tmp = f.read(1)
                code = tmp[0]
                cur += 3
                if code == 187:
                    data = f.read(field_len - 1)
                    cur += field_len - 1
                    if len(data) != field_len - 1:
                        f.close()
                        return ret
                else:
                    f.seek(field_len - 1, 1)
                    cur += field_len - 1
                    continue
                if code == 187:
                    count += 1
                    csi = CSI_Data(data)
                    ret.append(csi)

    except IOError as err:
        print(err)
    return ret
